<template>
    <div class="">
      <el-button class="getmsgbtn" @click="initSocket">获取数据</el-button>
      <el-button class="getmsgbtn" @click="close">关闭连接</el-button>
      <el-button class="getmsgbtn" @click="close">连接</el-button>
<!--      <el-input type="text" class="msgtext" v-model="this.resultmsg"></el-input>-->
      <div>{{this.resultmsg}}</div>
    </div>
</template>

<script>
  let socket;
  export default {
    name: "Tag03",
    websock: "",
    data() {
      return {
        resultmsg: "",
        flag: true,
      }
    },
    methods: {
      initSocket() {
        socket = new WebSocket("ws://127.0.0.1:1470/chat/msg");
        // socket = new WebSocket("ws://224.100.1.8:6008/chat/msg");
        socket.onmessage = this.websocketonmessage;
        socket.onerror = this.websocketonerror;
        socket.onopen = this.websocketonopen;
        //socket.onclose = this.websocketclose;

      },
      //关闭websocket
      close() {
        socket.onclose = this.websocketclose;
        socket.close();
      },
      websocketonopen() {
        this.websocketsend("连接成功");
        console.log("连接成功")
      },
      websocketonerror(e) {
        console.log('WebSocket连接失败', e);
      },
      // 数据接收
      websocketonmessage(e) {
        console.log(e.data);
        // window.print(e.data);
        this.resultmsg = this.resultmsg + "\n\r"+e.data;

      },
      // 数据发送
      websocketsend(Data) {
        let json = {"toName": "张三", "message": Data};
        // var chatdata = sessionStorage.getItem(toName);
        // sessionStorage.setItem(toName,str);
        //发送数据
        // ws.send(JSON.stringify(json));
        socket.send(JSON.stringify(json));
      },
      // 关闭
      websocketclose(e) {
        console.log('已关闭连接', e);
      }

    }
  }
</script>

<style scoped>

</style>
